<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <!--                  <el-form-item label="主题" prop="topic">-->
            <!--                    <el-input v-model="queryParams.topic" placeholder="请输入主题" clearable @keyup.enter.native="handleQuery"/>-->
            <!--                  </el-form-item>-->
            <el-form-item label="出入库时间" prop="handleTime">
                <el-date-picker clearable v-model="queryParams.handleTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择出入库时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="审核状态" prop="audit">
                <el-input v-model="queryParams.audit" placeholder="请输入审核状态" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['basic:order:add']">申领耗材
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                           v-hasPermi="['basic:order:edit']">修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                           @click="handleDelete" v-hasPermi="['basic:order:remove']">删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                           v-hasPermi="['basic:order:export']">导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-drawer title="申领耗材" :visible.sync="table" direction="rtl" size="50%">
            <el-table v-loading="consumableLoading" :data="consumableList" style="width: 100%">
                <el-table-column label="耗材名称" align="center" prop="name"/>

                <el-table-column label="型号" align="center" prop="model">
                    <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.model"
                                  placeholder="请输入型号"></el-input>
                        <span v-else>{{ scope.row.model }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="规格" align="center" prop="rule">
                    <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.rule" placeholder="请输入规格"></el-input>
                        <span v-else>{{ scope.row.rule }}</span>
                    </template>
                </el-table-column>


                <el-table-column label="单位" align="center" prop="consumeUnit">
                    <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.consumeUnit"
                                  placeholder="请输入单位"></el-input>
                        <span v-else>{{ scope.row.consumeUnit }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="厂商" align="center" prop="vender">
                    <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.vender"
                                  placeholder="请输入厂商"></el-input>
                        <span v-else>{{ scope.row.vender }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="数量" align="center" prop="number" width="210">
                    <template slot-scope="scope">
                        <el-input-number v-if="scope.row.editing" v-model="scope.row.number" :min="1"
                                         label="请输入数量"></el-input-number>
                        <span v-else>{{ scope.row.number }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="阈值" align="center" prop="warningNumber" width="210">
                    <template slot-scope="scope">
                        <el-input-number v-if="scope.row.editing" v-model="scope.row.warningNumber" :min="1"
                                         label="请输入警戒阈值"></el-input-number>
                        <span v-else>{{ scope.row.warningNumber }}</span>
                    </template>
                </el-table-column>


                <el-table-column label="备注" align="center" prop="remark">
                    <template slot-scope="scope">
                        <el-input v-if="scope.row.editing" v-model="scope.row.remark"
                                  placeholder="请输入备注"></el-input>
                        <span v-else>{{ scope.row.remark }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
                    <template slot-scope="scope">
                        <el-button type="primary" plain size="mini"
                                   @click="addToSelected(scope.row)"
                                   v-hasPermi="['basic:consumable:edit']">加入
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="consumableTotal>0" :total="consumableTotal" :page.sync="consumableQueryParams.pageNum"
                        :limit.sync="consumableQueryParams.pageSize" @pagination="getListConsumable"/>

            <!-- 待选择耗材列表区域 -->
            <div v-if="selectedConsumables.length > 0"
                 style="margin-top: 20px; border-top: 1px solid #ebeef5; padding-top: 20px; width: 100%;">
                <div style="margin-bottom: 10px; font-weight: bold;">
                    <i class="el-icon-shopping-cart-2" style="margin-right: 5px;"></i>
                    已选择耗材 ({{ selectedConsumables.length }}个)
                </div>
                <el-table :data="selectedConsumables" style="width: 100%; min-width: 1600px;" max-height="300">
                    <el-table-column label="耗材名称" align="center" prop="name" width="230"/>
                    <el-table-column label="型号" align="center" prop="model" width="170"/>
                    <el-table-column label="规格" align="center" prop="rule" width="170"/>
                    <el-table-column label="单位" align="center" prop="consumeUnit" width="100"/>
                    <el-table-column label="厂商" align="center" prop="vender" width="170"/>
                    <el-table-column label="申请数量" align="center" width="240">
                        <template slot-scope="scope">
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <el-input-number v-model="scope.row.number" :min="1" size="mini"
                                                 @change="updateSelectedConsumableNumber(scope.$index, scope.row)"
                                                 :validate-event="true" label="请输入数量"
                                                 :controls="true" :step="1">
                                </el-input-number>
                                <span v-if="scope.row.originalNumber"
                                      style="font-size: 12px; color: #909399; background: #f5f7fa; padding: 2px 6px; border-radius: 3px;">
                                    库存: {{ scope.row.originalNumber }}
                                </span>
                            </div>
                            <div v-if="scope.row.hasError" style="color: #f56c6c; font-size: 12px; margin-top: 2px;">
                                ⚠️ 申请数量 {{ scope.row.number }} 超过了库存数量 {{
                                    getThresholdLimit(scope.row)
                                }}，提交时会被拒绝
                            </div>
                            <div v-else-if="scope.row.number > getThresholdLimit(scope.row)"
                                 style="color: #f56c6c; font-size: 12px; margin-top: 2px;">
                                申请数量不能超过阈值限制 {{ getThresholdLimit(scope.row) }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
                        <template slot-scope="scope">
                            <el-button size="mini" type="danger" icon="el-icon-delete"
                                       @click="removeSelectedConsumable(scope.$index)">移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="text-align: right; margin-top: 15px;">
                    <el-button type="primary" size="medium" @click="submitSelectedConsumables"
                               :disabled="selectedConsumables.length === 0">
                        <i class="el-icon-check" style="margin-right: 5px;"></i>
                        确认提交申领 ({{ selectedConsumables.length }}个耗材)
                    </el-button>
                </div>
            </div>

        </el-drawer>

        <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="订单号" align="center" prop="id"/>
            <el-table-column label="主题" align="center" prop="topic"/>
            <el-table-column label="出入库时间" align="center" prop="handleTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
<!--            <el-table-column label="业务类型" align="center" prop="businessType"/>-->
            <el-table-column label="合计数量" align="center" prop="number"/>
            <el-table-column label="申请账户" align="center" prop="nickName"/>
            <!--            <el-table-column label="类型" align="center" prop="type"/>-->
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="库管人员" align="center" prop="inventoryKeeper"/>

            <el-table-column label="申请状态" align="center" prop="audit">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.basic_consumable_order_status_dict" :value="scope.row.audit"/>
                </template>
            </el-table-column>


            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                               v-hasPermi="['basic:order:edit']">修改
                    </el-button>

                    <el-button size="mini" type="text" icon="el-icon-view" @click="showConsumablesDetail(scope.row)"
                               v-hasPermi="['basic:order:edit']">申请明细
                    </el-button>

                    <!-- audit=0 时，管理员和仓库管理员都显示通过/出库和驳回按钮 -->
<!--                    <template v-if="scope.row.audit === 0">-->
<!--                        <el-button size="mini" type="text" icon="el-icon-close" @click="handleReject(scope.row)"-->
<!--                            v-hasPermi="['basic:order:edit']">通过-->
<!--                        </el-button>-->
<!--                        <el-button size="mini" type="text" icon="el-icon-close" @click="handleReject(scope.row)"-->
<!--                            v-hasPermi="['basic:order:edit']">驳回-->
<!--                        </el-button>-->
<!--                    </template>-->

<!--                    <template v-if="scope.row.audit === 1">-->
<!--                        <el-button size="mini" type="text" icon="el-icon-close" @click="handleReject(scope.row)"-->
<!--                                   v-hasPermi="['basic:order:edit']">出库-->
<!--                        </el-button>-->
<!--                        <el-button size="mini" type="text" icon="el-icon-close" @click="handleReject(scope.row)"-->
<!--                                   v-hasPermi="['basic:order:edit']">驳回-->
<!--                        </el-button>-->
<!--                    </template>-->

                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                               v-hasPermi="['basic:order:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>

        <!-- 添加或修改耗材出库对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="主题" prop="topic">
                    <el-input v-model="form.topic" placeholder="请输入主题"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-form-item label="库管人员" prop="inventoryKeeper">
                    <el-input v-model="form.inventoryKeeper" placeholder="请输入库管人员"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 耗材详情展示弹窗 -->
        <el-dialog title="耗材明细" :visible.sync="consumablesDetailDialog" width="800px" append-to-body>
            <div class="consumables-detail-container">
                <!-- 统计信息 -->
                <div class="summary-info">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <div class="info-item">
                                <span class="label">耗材种类：</span>
                                <span class="value">{{ currentConsumables.length }} 条</span>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="info-item">
                                <span class="label">总数量：</span>
                                <span class="value">{{ getTotalQuantity(currentConsumables) }}</span>
                            </div>
                        </el-col>
                    </el-row>
                </div>

                <!-- 耗材列表 -->
                <el-table :data="currentConsumables" border stripe style="width: 100%; margin-top: 20px;">
                    <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
                    <el-table-column label="耗材名称" prop="name" align="center"></el-table-column>
                    <el-table-column label="型号" prop="model" align="center" width="120"></el-table-column>
                    <el-table-column label="规格" prop="rule" align="center" width="100"></el-table-column>
                    <el-table-column label="申请数量" prop="number" align="center" width="100"></el-table-column>
                    <el-table-column label="单位" prop="consumeUnit" align="center" width="80"></el-table-column>
                </el-table>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="consumablesDetailDialog = false">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listOrder, getOrder, delOrder, addOrder, updateOrder, getOrderS} from "@/api/basic/order";
import {listConsumable} from "@/api/basic/consumable";
import {copyObj} from "@/utils/zzDouUtils/objUtil";

export default {
    name: "Order",
    dicts: ['basic_consumable_order_status_dict'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 耗材出库表格数据
            orderList: [],
            consumableList: [],
            // 耗材明细相关数据字段
            consumableTotal: 0,
            consumableLoading: false,
            consumableQueryParams: {
                pageNum: 1,
                pageSize: 10
            },
            // 待选择耗材列表
            selectedConsumables: [],


            queryConsumablesParams: {
                orderId: null,//订单id
                selectedConsumables: [],//选择的耗材
            },

            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 耗材详情展示弹窗
            consumablesDetailDialog: false,
            // 当前展示的耗材明细数据
            currentConsumables: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                topic: null,
                handleTime: null,
                businessType: null,
                number: null,
                price: null,
                userId: null,
                type: null,
                assetIds: null,
                assetIdns: null,
                inventoryKeeper: null,
                audit: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                topic: [
                    { required: true, message: '请输入主题', trigger: 'blur' },
                    { min: 2, max: 100, message: '主题长度应在2-100个字符之间', trigger: 'blur' }
                ],
            },
            table: false
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询耗材出库列表 */
        getList() {
            this.loading = true;
            listOrder(this.queryParams).then(response => {
                this.orderList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },

        // 统计辅助方法
        getUniqueCount(list, key) {
            if (!list || !Array.isArray(list) || !key) return 0
            const uniqueValues = new Set(list.map(item => item[key]).filter(val => val != null))
            return uniqueValues.size
        },

        getTotalQuantity(list) {
            if (!list || !Array.isArray(list)) return 0
            return list.reduce((total, item) => total + (Number(item.number) || 0), 0)
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                topic: null,
                handleTime: null,
                businessType: null,
                number: null,
                price: null,
                userId: null,
                type: null,
                assetIds: null,
                assetIdns: null,
                remark: null,
                inventoryKeeper: null,
                audit: null,
                createTime: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.getListConsumable();
            this.reset();
            this.table = true
            this.title = "添加耗材出库";
        },
        /** 查询耗材明细列表 */
        getListConsumable() {
            this.consumableLoading = true;
            listConsumable(this.consumableQueryParams).then(response => {
                this.consumableList = response.rows;
                this.consumableTotal = response.total;
                this.consumableLoading = false;
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            if (row.id) {
                this.form = copyObj(row);
            } else {
                this.form = copyObj(this.listOrder.filter(item => {
                    return item.id === this.ids
                })[0])
            }
            this.open = true;
            this.title = "修改耗材出库";
        },
        /** 提交按钮 */
        submitForm() {
            // 优先进行表单验证
            this.$refs["form"].validate(valid => {
                if (!valid) {
                    this.$message.warning('请检查表单填写是否完整');
                    return;
                }

                // 判断是添加还是修改操作
                const isEdit = this.form.id != null;
                const actionText = isEdit ? '修改' : '添加';

                // 执行实际提交操作的函数
                const executeSubmit = () => {
                    // 可以选择将参数对象也添加到submitData中一起提交
                    this.form.selectedConsumables = this.selectedConsumables;
                    console.log('提交的查询参数对象：', this.form);

                    // 根据form.id判断调用添加还是修改接口
                    const apiCall = isEdit ? updateOrder(this.form) : addOrder(this.form);

                    apiCall.then(response => {
                        this.$modal.msgSuccess(`${actionText}成功`);
                        // 清空已选择列表
                        this.selectedConsumables = [];
                        // 关闭申领耗材抽屉
                        this.table = false;
                        // 关闭表单弹窗
                        this.open = false;
                        // 刷新订单列表
                        this.getList();
                    }).catch(error => {
                        this.$modal.msgError(`${actionText}失败：` + (error.message || '未知错误'));
                    });
                };

                // 判断是否需要确认弹窗
                if (isEdit) {
                    // 修改操作直接提交，不需要确认弹窗
                    executeSubmit();
                } else {
                    // 添加操作才显示确认弹窗
                    const confirmText = `确认添加 ${this.selectedConsumables.length} 项耗材的申领申请？`;
                    this.$modal.confirm(confirmText).then(() => {
                        executeSubmit();
                    }).catch(() => {
                        // 用户取消操作
                    });
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除耗材出库编号为"' + ids + '"的数据项？').then(function () {
                return delOrder(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('basic/order/export', {
                ...this.queryParams
            }, `order_${new Date().getTime()}.xlsx`)
        },

        /** 添加耗材到已选择列表 */
        addToSelected(row) {
            // 检查是否已经选择
            const index = this.selectedConsumables.findIndex(item => item.id === row.id);
            if (index > -1) {
                this.$message.warning('该耗材已经添加到选择列表中');
                return;
            }

            // 获取阈值限制（使用原始数量作为阈值限制）
            const thresholdLimit = this.getThresholdLimit(row);

            // 创建新对象，添加默认数量和错误状态
            const newConsumable = {
                ...row,
                number: 1, // 默认数量为1
                originalNumber: row.number || row.stockNumber || row.warningNumber || 999, // 保存原始数量
                hasError: false // 初始化错误状态
            };

            this.selectedConsumables.push(newConsumable);
            this.$message.success(`耗材已添加到选择列表（库存限制：${thresholdLimit}）`);
        },

        // 更新已选择耗材的数量（带校验）
        updateSelectedConsumableNumber(index, row) {
            const number = row.number;
            const thresholdLimit = this.getThresholdLimit(row);

            if (number >= 1 && number <= thresholdLimit) {
                // 正常范围内的数量，允许编辑
                this.selectedConsumables[index].number = number;
                this.selectedConsumables[index].hasError = false;
            } else if (number > thresholdLimit) {
                // 超过阈值，只设置错误状态，但不强制重置
                this.selectedConsumables[index].number = number;
                this.selectedConsumables[index].hasError = true;
                this.$message.warning(`警告：申请数量 ${number} 超过了库存数量 ${thresholdLimit}，提交时会被拒绝`);
            } else if (number < 1) {
                // 小于1的数量，不允许
                this.selectedConsumables[index].number = 1;
                this.selectedConsumables[index].hasError = false;
                this.$message.warning('申请数量不能小于1');
            }
        },

        // 获取耗材阈值限制（始终返回原始数量）
        getThresholdLimit(row) {
            // 优先使用originalNumber，如果没有则使用原始的其他字段，默认值为999
            return row.originalNumber || row.stockNumber || row.warningNumber || row.number || 999;
        },

        /** 从已选择列表中移除耗材 */
        removeSelectedConsumable(index) {
            this.selectedConsumables.splice(index, 1);
            this.$message.success('耗材已从选择列表中移除');
        },


        /** 确认提交申领耗材 */
        submitSelectedConsumables() {
            if (this.selectedConsumables.length === 0) {
                this.$message.warning('请先选择要申领的耗材');
                return;
            }

            // 验证所有耗材数量是否有效
            const invalidItems = this.selectedConsumables.filter(item =>
                item.number < 1 || item.number > this.getThresholdLimit(item)
            );

            if (invalidItems.length > 0) {
                this.$message.warning('存在无效的申领数量，请检查后重试');
                return;
            }

            this.open = true;
        },
        generateOrderNumber() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const datePart = `${year}${month}${day}`;

            // Generate 6-digit random number
            const randomPart = Math.floor(100000 + Math.random() * 900000);

            return `OUT${datePart}${randomPart}`;
        },

        // 打开耗材详情展示弹窗
        showConsumablesDetail(row) {
            // 先获取耗材明细数据
            getOrderS(row.id).then(response => {
                this.currentConsumables = response.data || []
                this.consumablesDetailDialog = true
            }).catch(error => {
                this.$message.error('获取耗材明细失败：' + (error.message || '未知错误'))
            })
        },
        // 处理步骤
        handleStep(row){
            console.log(row)
        }
    }
};
</script>
